package org.meb.speedway.ws;

import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.meb.speedway.config.SpeedwayDatabase;
import org.meb.speedway.model.common.IntEvent;
import org.meb.speedway.model.common.IntEvent_;
import org.meb.speedway.process.EventTaskProcessorChain;

//@Stateless
//@WebService
public class EventWebService {

	@Inject
	@SpeedwayDatabase
	private EntityManager em;

	@WebMethod
	public void insertEventTask(@WebParam(name = "eventUri") String eventUri) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<IntEvent> cq = cb.createQuery(IntEvent.class);
		Root<IntEvent> evta = cq.from(IntEvent.class);
		cq.where(cb.equal(cb.lower(evta.get(IntEvent_.eventUri)), eventUri.toLowerCase()));
		List<IntEvent> list = em.createQuery(cq).getResultList();
		if (list.size() == 0) {
			IntEvent intEvent = new IntEvent();
			intEvent.setEventUri(eventUri);
			intEvent.getFingerprint().setInsertDate(new Date());
			intEvent.setStatus(IntEvent.Status.REGISTERED);
			em.persist(intEvent);
			em.flush();

			EventTaskProcessorChain.getInstance().process(intEvent);
		}
	}
}
